import time
import logging
from datetime import datetime, timedelta, timezone
import pytest
from common.request_util_test import RequestUtil
from common.test_yaml_util_test import YamlUtil
from common.read_values import TextUtil
from common.extension_component import ExtensionComponent, InstallationParams
from config import datas


class Testlogging:
    flag_logging_installed_stat = 0  # flag置0表示logging-package之前未安装，需要在本测试套临时安装。置1表示之前已安装，无需安装
    url_verify = "/rest/logging/v1/resource-list"
    url_unify = "/clusters/host"

    @pytest.mark.normal
    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('valuesinfo',
                             TextUtil().read_value_yaml('values_logging.yaml'))
    def test_install_logging(self, valuesinfo):
        res = ExtensionComponent.is_installed('logging')
        if res == False:
            # 安装并检查
            uri_install = "/rest/application-management/v1beta1/helm-releases/namespace/{namespace}/release/{release}"
            uri_install = uri_install.replace("{namespace}", datas.test_logging["namespace"])
            uri_install = uri_install.replace("{release}", datas.test_logging["release"])
            url_install = datas.baseUrl + uri_install
            method_install = "POST"
            headers_install = {"Content-Type": "application/json"}
            data_install = {
                "chartName": datas.test_logging["release"],
                "repoName": datas.test_logging["repoName"],
                "version": datas.test_logging["version"],
                "values": valuesinfo["data"],
            }
            params = InstallationParams(url_install, method_install, headers_install, data_install)
            res_install = ExtensionComponent.installing(params, datas.baseUrl + self.url_verify)
            assert res_install == True

    @pytest.mark.normal
    @pytest.mark.logging
    def test_get_login_logging(self):
        # 检查日志模块登录成功
        url_login = '/container_platform/logging/logSearch'
        url = datas.baseUrl + url_login
        req = RequestUtil().send_request('get', url)
        assert req.status_code == 200

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/1_get_logging_of_namespace.yaml'))
    def test_get_logging_of_namespace(self, logginginfo):
        # 查询命名空间下的日志-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'namespace': urlinfo['namespace'], 'endtime': str(endtime), 'starttime': str(starttime),
                        'level': urlinfo['level'], 'keyword': urlinfo['keyword']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/1_get_logging_of_namespace_exception.yaml'))
    def test_get_logging_of_namespace_exception(self, logginginfo):
        # 查询命名空间下的日志-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'namespace': urlinfo['namespace'], 'endtime': str(endtime), 'starttime': str(starttime),
                        'level': urlinfo['level'], 'keyword': urlinfo['keyword']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo', YamlUtil().read_testcase_yaml('v25.06/logging/2_get_logging_of_pod.yaml'))
    def test_get_logging_of_pod(self, logginginfo):
        # 查询pod下的日志-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'namespace': urlinfo['namespace'], 'pod': urlinfo['pod'], 'endtime': str(endtime),
                        'starttime': str(starttime), 'level': urlinfo['level'], 'keyword': urlinfo['keyword']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/2_get_logging_of_pod_exception.yaml'))
    def test_get_logging_of_pod_exception(self, logginginfo):
        # 查询pod下的日志-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'namespace': urlinfo['namespace'], 'pod': urlinfo['pod'], 'endtime': str(endtime),
                        'starttime': str(starttime), 'level': urlinfo['level'], 'keyword': urlinfo['keyword']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/3_get_logging_of_container.yaml'))
    def test_get_logging_of_container(self, logginginfo):
        # 查询container下的日志-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'namespace': urlinfo['namespace'], 'pod': urlinfo['pod'], 'container': urlinfo['container'],
                        'endtime': str(endtime), 'starttime': str(starttime), 'level': urlinfo['level'],
                        'keyword': urlinfo['keyword']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/3_get_logging_of_container_exception.yaml'))
    def test_get_logging_of_container_exception(self, logginginfo):
        # 查询container下的日志-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'namespace': urlinfo['namespace'], 'pod': urlinfo['pod'], 'container': urlinfo['container'],
                        'endtime': str(endtime), 'starttime': str(starttime), 'level': urlinfo['level'],
                        'keyword': urlinfo['keyword']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo', YamlUtil().read_testcase_yaml('v25.06/logging/4_get_logging_filelist.yaml'))
    def test_get_logging_filelist(self, logginginfo):
        # 查询日志文件列表-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url']
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/4_get_logging_filelist_exception.yaml'))
    def test_get_logging_filelist_exception(self, logginginfo):
        # 查询日志文件列表-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url']
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/5_get_logging_resourcelist.yaml'))
    def test_get_logging_resourcelist(self, logginginfo):
        # 查询资源列表-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url'].replace('{namspace}', datas.test_logging['namespace'])
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/5_get_logging_resourcelist_exception.yaml'))
    def test_get_logging_resourcelist_exception(self, logginginfo):
        # 查询资源列表-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url'].replace('{namspace}', datas.test_logging['namespace'])
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/6_get_logging_by_filename.yaml'))
    def test_get_logging_by_filename(self, logginginfo):
        # 根据文件名查询日志-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'starttime': str(starttime), 'endtime': str(endtime), 'level': urlinfo['level'],
                        'filename': urlinfo['filename']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/6_get_logging_by_filename_exception.yaml'))
    def test_get_logging_by_filename_exception(self, logginginfo):
        # 根据文件名查询日志-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        starttime = str((datetime.now(tz=timezone.utc) - timedelta(minutes=10)).timestamp()).split('.')[0]
        endtime = str(datetime.now(tz=timezone.utc).timestamp()).split('.')[0]
        urlinfo = datas.test_logging
        replacements = {'starttime': str(starttime), 'endtime': str(endtime), 'level': urlinfo['level'],
                        'filename': urlinfo['filename']}
        url = base_url + f"{logginginfo['request']['url'].format_map(replacements)}"
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo', YamlUtil().read_testcase_yaml('v25.06/logging/7_get_logging_sources.yaml'))
    def test_get_logging_sources(self, logginginfo):
        # 采集任务相关接口-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url']
        method = logginginfo['request']['method']
        if 'headers' in logginginfo['request']:
            req = RequestUtil().send_request(method, url, headers=logginginfo['request']['headers'],
                                             json=logginginfo['request']['data'])
        else:
            req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/7_get_logging_sources_exception.yaml'))
    def test_get_logging_sources_exception(self, logginginfo):
        # 采集任务相关接口-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url']
        method = logginginfo['request']['method']
        if 'headers' in logginginfo['request']:
            req = RequestUtil().send_request(method, url, headers=logginginfo['request']['headers'],
                                             json=logginginfo['request']['data'])
        else:
            req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/8_get_logging_context_details.yaml'))
    def test_get_context_details(self, logginginfo):
        # 获取日志上下文详情-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url'].replace('{filename}', datas.test_logging['filename'])
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo', YamlUtil().read_testcase_yaml(
        'v25.06/logging/8_get_logging_context_details_exception.yaml'))
    def test_get_context_details_exception(self, logginginfo):
        # 获取日志上下文详情-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url'].replace('{filename}', datas.test_logging['filename'])
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo', YamlUtil().read_testcase_yaml('v25.06/logging/9_get_logging_other.yaml'))
    def test_get_logging_other(self, logginginfo):
        # 获取日志其他接口-正常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url']
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.logging
    @pytest.mark.parametrize('logginginfo',
                             YamlUtil().read_testcase_yaml('v25.06/logging/9_get_logging_other_exception.yaml'))
    def test_get_logging_other_exception(self, logginginfo):
        # 获取日志其他接口-异常
        base_url = datas.baseUrl + Testlogging.url_unify
        url = base_url + logginginfo['request']['url']
        method = logginginfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == logginginfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.abnormal
    @pytest.mark.logging
    def test_uninstall_logging(self):
        # 卸载并检查
        uri_delete = ("/clusters/host/rest/application-management/v1beta1/helm-releases/"
                      "namespace/{namespace}/release/{release}")
        uri_delete = uri_delete.replace("{namespace}", datas.test_logging["namespace"])
        uri_delete = uri_delete.replace("{release}", datas.test_logging["release"])
        url_delete = datas.baseUrl + uri_delete
        method_delete = "DELETE"
        headers_delete = {"Content-Type": "application/json"}
        params = InstallationParams(url_delete, method_delete)
        res_uninstall = ExtensionComponent.uninstall(params, datas.baseUrl + self.url_verify)
        assert res_uninstall == True
